Page({

  /**
   * Page initial data
   */
  data: {
    recoding: false,
    start: true,
    percent: 0,
    currentTime: '00:00',
    duration: '00:00',
    show: false,
    fileName: '',
    type: 0,
    finish: false,
    bgmList: [],
    showBgm: false,
    radio: '',
    bgmName: ''
  },

  /**
   * Lifecycle function--Called when page load
   */
  onLoad(options) {
    console.log(options);
    this.setData({
      type: options.type
    })
    wx.request({
      url: `http://localhost:1234/creator/setMute?id=${options.id}`,
      method: "GET",
      header: {
        'content-type': "application/json"
      },
      success: (res) => {
        console.log(res.data.word)
        let code = res.data.word.split(/[(\r\n)\r\n]+/); // 根据换行或者回车进行识别
        code.forEach((item, index) => { // 删除空项
          if (!item) {
            code.splice(index, 1);
          }
        })
        if (res.data.code == 200) {
          this.setData({
            muteName: options.type == 4 ? options.image : res.data.fileName,
            word: code
          })
        }
      },
      fail: (err) => {
        console.log(err);
      }
    })

  },

  /**
   * Lifecycle function--Called when page is initially rendered
   */
  onReady() {
    this.videoContext = wx.createVideoContext('myVideo')
  },

  /**
   * Lifecycle function--Called when page show
   */
  onShow() {
    var that = this;
    //获取全局唯一的录音管理器 RecorderManager实例
    that.recorderManager = wx.getRecorderManager()
    that.recorderManager.onStop((res) => {
      that.setData({
        tempFilePath: res.tempFilePath // 文件临时路径
      })
      console.log('获取到文件：' + that.data.tempFilePath)
      const {
        tempFilePath
      } = res

      wx.saveFile({
        tempFilePath: tempFilePath,
        success: function (res) {
          // 保存成功，res.savedFilePath 是保存后的文件路径
          var savedFilePath = res.savedFilePath;
          console.log(savedFilePath)
          that.setData({
            show: true
          })
          if (that.data.type == 4) {
            wx.uploadFile({
              filePath: savedFilePath,
              name: 'file',
              timeout: 180000,
              url: `http://localhost:1234/creator/together?name=${that.data.muteName}`,
              success: (res) => {
                console.log(JSON.parse(res.data));
                if (JSON.parse(res.data).code == 200) {
                  console.log(JSON.parse(res.data).fileName)
                  that.setData({
                    fileName: `${JSON.parse(res.data).fileName}`,
                    finish: true
                  })
                }
              },
              fail: res => {
                console.log(res);
              }
            })
          }
          else {
            wx.uploadFile({
              filePath: savedFilePath,
              name: 'file',
              url: `http://localhost:1234/creator/merge?muteName=${that.data.muteName}`,
              success: (res) => {
                if (JSON.parse(res.data).code == 200) {
                  console.log(JSON.parse(res.data).fileName)
                  that.setData({
                    fileName: `${JSON.parse(res.data).fileName}`,
                    finish: true
                  })

                }
              },
              fail: res => {
                console.log('fail')
              }
            })
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    })
    this.recorderManager.onError((res) => {
      console.log('录音失败了！')
    })
  },

  /**
   * Lifecycle function--Called when page hide
   */
  onHide() {

  },

  /**
   * Lifecycle function--Called when page unload
   */
  onUnload() {

  },

  /**
   * Page event handler function--Called when user drop down
   */
  onPullDownRefresh() {

  },

  /**
   * Called when page reach bottom
   */
  onReachBottom() {

  },

  /**
   * Called when user click on the top right corner to share
   */
  onShareAppMessage() {

  },

  //开始, 暂停, 继续录音
  recode: function () {
    this.setData({
      recoding: !this.data.recoding
    })
    if (this.data.recoding && this.data.start) {
      this.setData({
        start: false
      })
      console.log('start')
      this.recorderManager.start({
        duration: 60000,
        sampleRate: 16000, //采样率，有效值 8000/16000/44100
        numberOfChannels: 1, //录音通道数，有效值 1/2
        encodeBitRate: 96000, //编码码率
        format: 'mp3', //音频格式，有效值 aac/mp3
        frameSize: 50, //指定帧大小
        audioSource: 'auto' //指定录音的音频输入源，可通过 wx.getAvailableAudioSources() 获取
      })
      this.videoContext.play();
    } else if (this.data.recoding && !this.data.start) {
      console.log('resume')
      this.recorderManager.resume()
      this.videoContext.play();
    } else {
      console.log('pause')
      this.recorderManager.pause()
      this.videoContext.pause();
    }
  },

  //点击完成
  finished: function () {
    this.setData({
      recoding: false
    })
    console.log('stop')
    this.videoContext.pause()
    this.recorderManager.stop()
  },

  //重录
  again: function () {
    this.onLoad();
    this.setData({
      recoding: false,
      start: true
    })
    this.videoContext.seek(0)
    this.videoContext.stop()
    this.setData({
      percent: 0,
      currentTime: '00:00'
    })
  },

  timeUpdate: function (e) {
    if (!this.data.start) {
      this.setData({
        percent: (e.detail.currentTime / e.detail.duration) * 100
      })

      let currentTime = Math.floor(e.detail.currentTime)
      let minutes = Math.floor(currentTime / 60)
      let seconds = Math.floor(currentTime % 60)
      let time = ''
      if (minutes < 10 && seconds < 10) {
        time = `0${minutes}:0${seconds}`
      }
      else if (minutes >= 10 && seconds < 10) {
        time = `${minutes}:0${seconds}`
      }
      else if (minutes < 10 && seconds >= 10) {
        time = `0${minutes}:${seconds}`
      }
      else {
        time = `${minutes}:${seconds}`
      }
      this.setData({
        currentTime: time
      })
    }
  },
  loaded: function (e) {
    console.log(e.detail.duration)
    let duration = Math.floor(e.detail.duration)
    let minutes = Math.floor(duration / 60)
    let seconds = Math.floor(duration % 60)
    let time = ''
    if (minutes < 10 && seconds < 10) {
      time = `0${minutes}:0${seconds}`
    }
    else if (minutes >= 10 && seconds < 10) {
      time = `${minutes}:0${seconds}`
    }
    else if (minutes < 10 && seconds >= 10) {
      time = `0${minutes}:${seconds}`
    }
    else {
      time = `${minutes}:${seconds}`
    }
    this.setData({
      duration: time
    })
  },

  getUserInfo(event) {
    console.log(event.detail);
    wx.navigateTo({
      url: `../publish/publish?fileName=${this.data.fileName}`
    })
  },

  onClose() {
    this.setData({ close: false });
  },

  getBgm: function () {
    wx.request({
      url: `http://localhost:1234/creator/bgm`,
      method: "GET",
      success: (res) => {
        console.log(res.data);
        this.setData({
          bgmList: res.data,
          showBgm: true
        })
      }
    })
  },

  onChange(event) {
    console.log(event.detail)
    this.setData({
      radio: event.detail,
      bgmName: event.detail
    });
  },

  getBgmInfo(event) {
    this.setData({
      finish: false
    })
    wx.request({
      url: `http://localhost:1234/creator/addBgm?name=${this.data.fileName}&bgmName=${this.data.bgmName}`,
      method: "GET",
      success: (res) => {
        console.log(res)
        if (res.data.code == 200) {
          this.setData({
            fileName: res.data.fileName,
            finish: true
          })
        }
      }
    })
  },

  bgmClose() {
    this.setData({ showBgm: false });
  }
})